/**
 * Copyright 2010 Marcus Calverley <marcus@calverley.dk>
 *
 * This file is part of I'm Busy.
 *
 * I'm Busy is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * I'm Busy is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with I'm Busy.  If not, see <http://www.gnu.org/licenses/>.
 */
package dk.lmz.android.busy;

import java.util.ArrayList;
import java.util.HashSet;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.DialogPreference;
import android.util.AttributeSet;

/**
 * Special preference for selecting which calendars should be monitored for events.
 *
 * @author Marcus Calverley <marcus@calverley.dk>
 */
public class SelectCalendarsPreference extends DialogPreference
{
	private final String[] projection = new String[] { "_id", "displayName" };
	private ArrayList<Integer> calendarIds;
	private String[] calendarNames;
	private boolean[] calendarSelections;
	private HashSet<Integer> selectedCalendars;

	public SelectCalendarsPreference(Context context, AttributeSet attrs)
	{
		super(context, attrs);
	}

	@Override
	protected void onDialogClosed(boolean positiveResult)
	{
		if (positiveResult)
		{
			String oldValue = getPersistedString("");
			String newValue = BusyService.buildSelectedCalendarPref(selectedCalendars);

			// If something's changed we update the saved value
			if (!oldValue.equals(newValue))
			{
				callChangeListener(newValue);
				persistString(newValue);
			}
			else
			{
				try
				{
					BusyService.checkConfiguration(getContext());
				}
				catch (CalendarsNotAvailableException e)
				{
					BusyService.log("Calendars not available");
				}
			}
		}
	}

	@Override
	protected void showDialog(Bundle state)
	{
		ArrayList<String> calendarNames = new ArrayList<String>();
		ArrayList<Boolean> calendarSelections = new ArrayList<Boolean>();

		// Start by getting the calendars already set in preferences
		selectedCalendars = BusyService.getSelectedCalendars(getContext());

		// Get calendars available
		Cursor cursor = getContext().getContentResolver().query(BusyService.calendars, projection, null, null, null);

		// Reset calendar IDs
		calendarIds = new ArrayList<Integer>();

		if (cursor != null)
		{
			while (cursor.moveToNext())
			{
				calendarIds.add(cursor.getInt(0));
				calendarNames.add(cursor.getString(1));
				calendarSelections.add(selectedCalendars.contains(cursor.getInt(0)));
			}
			cursor.close();
		}

		// Get string array of calendar names
		this.calendarNames = calendarNames.toArray(new String[calendarNames.size()]);

		// Convert from Boolean[] to boolean[] -- stupid @%#& Java
		this.calendarSelections = new boolean[this.calendarNames.length];
		int i = 0;
		for (boolean selected : calendarSelections)
		{
			this.calendarSelections[i++] = selected;
		}
		super.showDialog(state);
	}

	@Override
	protected void onPrepareDialogBuilder(AlertDialog.Builder builder)
	{
		// Make a multiple choice dialog
		builder.setMultiChoiceItems(calendarNames, calendarSelections, new OnCalendarSelectClickListener());
	}

	private class OnCalendarSelectClickListener implements OnMultiChoiceClickListener
	{
		public void onClick(DialogInterface dialog, int which, boolean isChecked)
		{
			if (isChecked)
			{
				selectedCalendars.add(calendarIds.get(which));
			}
			else
			{
				selectedCalendars.remove(calendarIds.get(which));
			}
		}
	}
}
